package com.pomr.util.interceptor;



import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.pomr.model.sys.User;
import com.pomr.util.common.JWT;
import com.pomr.util.common.ResponseData;

/**
 * 拦截请求 验证token
 * @author Administrator
 *
 */
public class TokenInterceptor implements HandlerInterceptor{
	
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		System.out.println("开始拦截");
		//支持跨域请求
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "authorization, content-type");
        response.setHeader("Access-Control-Expose-Headers", "*");
		response.setCharacterEncoding("utf-8");
		
		
        ResponseData responseData = ResponseData.ok();
        
        //客户端将token封装在请求头中，格式为（Bearer后加空格）：Authorization：Bearer +userid+"||"+token+"||"+duetime
        final String authHeader = request.getHeader("Authorization");
        System.out.println(authHeader);
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
        	System.out.println("没有token");
        	responseData = ResponseData.tokenError();
            responseMessage(response, response.getOutputStream(), responseData);
            return false;
        }
        //去除Bearer 后部分
        String str = authHeader.substring(7);
        String[] strs = str.split("-&-");
        String token = null;
        String duetime = null;
        if(strs.length>=3){
        	token = strs[1];
        	duetime = strs[2];//过期时间
        }
        if(duetime!=null && !duetime.equals("")){//检查过期时间 如果小于5分钟 重新设置
        	//TODO 重新设置token 将原token记入黑名单
        }else{//没有设置过期时间
        	responseData = ResponseData.tokenError();
            responseMessage(response, response.getOutputStream(), responseData);
            return false;
        }
        //token不存在
        if(null != token) {
        	System.out.println("--------解析token");
        	User user = JWT.unsign(token, User.class);
        	String userid = strs[0];
            //解密token后的loginId与用户传来的loginId不一致，一般都是token过期
            if(null != userid && null != user) {
                if(Integer.parseInt(userid) == user.getId()) {
                	System.out.println("一致");
                    return true;
                }
                else{
                	System.out.println(userid+"------"+user.getId());
                	responseData = ResponseData.tokenError();
                    responseMessage(response, response.getOutputStream(), responseData);
                    return false;
                }
            }
            else
            {
            	System.out.println(userid+"------"+user);
            	responseData = ResponseData.tokenError();
                responseMessage(response, response.getOutputStream(), responseData);
                return false;
            }
        }
        else
        {
        	responseData = ResponseData.tokenError();
            responseMessage(response, response.getOutputStream(), responseData);
            return false;
        }
	}
	
	//请求不通过，返回错误信息给客户端  使用ServletOutputStream 不要使用PrintWriter 因为springmvc默认使用ServletOutputStream
    private void responseMessage(HttpServletResponse response, ServletOutputStream out, ResponseData responseData) throws Exception{
        String json = JSONObject.toJSONString(responseData);
        out.write(json.getBytes());
        out.flush();
        out.close();
    }
}
